package service

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"user-srv/basic/golbal"
	"user-srv/basic/model"
	"user-srv/handler/request"
	"user-srv/pkg"
)

func Register(c *gin.Context) {
	res := request.UserReq{}
	if err := c.ShouldBind(&res); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	user := model.User{

		Mobile:   res.Mobile,
		Password: pkg.Md5(res.Password),
	}

	golbal.DB.Debug().Create(&user)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

func Login(c *gin.Context) {
	res := request.UserReq{}
	if err := c.ShouldBind(&res); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user model.User

	golbal.DB.Debug().Where("mobile=?", user.Mobile).Find(&user)

	handler, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": handler,
	})
}
